package com.tiger.auth;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @program: jksj
 * @description:
 * @author: tigerJay
 * @create: 2022-02-04 15:39
 **/
public class AuthToken {
    private static  final long DEFAULT_EXPIRED_TIME_INTERVAL = 1*60*1000;
    private String token;
    private long createTime;
    private long expiredTimeInterval = DEFAULT_EXPIRED_TIME_INTERVAL;

    public AuthToken(String token,long createTime){
        this.token = token;
        this.createTime = createTime;
    }

    public String getToken() {
        return token;
    }

    /**
     * 获取方法调用token
     * @param baseUrl 请求url
     * @param createTime 请求时间
     * @param params 请求参数
     * @return token信息
     */
    public static AuthToken create(String baseUrl, long createTime, Map<String,String> params){
        String token = generateToken(generateFullUrl(baseUrl,createTime,params));
        AuthToken authToken = new AuthToken(token,System.currentTimeMillis());
        return authToken;
    }

    /**
     * 请求token是否过期
     * @return
     */
    public boolean isExpire(){
        return (System.currentTimeMillis() - createTime) > expiredTimeInterval;
    }

    /**
     * token是否匹配
     * @return
     */
    public boolean match(AuthToken authToken){
        return this.token.equals(authToken.getToken());
    }

    private static String generateToken(String fullUrl){
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            return new String(md5.digest(fullUrl.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String generateFullUrl(String baseUrl,long createTime,Map<String,String> params){
        StringBuilder sb = new StringBuilder(baseUrl);
        sb.append("&");
        sb.append("createTime=");
        sb.append(createTime);
        params.forEach((k,v) -> {
            sb.append("&");
            sb.append(k);
            sb.append("=");
            sb.append(v);
        });
        return sb.toString();
    }
}
